package com.xoa.dev.pz.service.impl;
/*
    created by 王志伟 on 2017/12/2

 */

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.dev.pz.dao.PzEasyAccidentMapper;
import com.xoa.dev.pz.dao.PzPersonMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.party.GridInfo;
import com.xoa.dev.pz.model.PzEasyAccident;
import com.xoa.dev.pz.model.PzEasyAccidentWithBLOBs;
import com.xoa.dev.pz.model.PzPerson;
import com.xoa.dev.pz.model.PzPersonWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.service.sys.SysLogService;
import com.xoa.service.users.UsersService;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PzEasyAccidentService {

    @Autowired
    private PzEasyAccidentMapper pzEasyAccidentMapper;
    @Resource
    private GridInfoMapper gridInfoMapper;

    @Autowired
    private PzPersonMapper pzPersonMapper;

    @Autowired
    public UsersService usersService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private MenuJdtMapper menuJdtMapper;

    public ToJson<PzEasyAccidentWithBLOBs> insertInformation(PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs, HttpServletRequest request){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<>(1, "error");
        //创建时间
        Date date = new Date();
        String creatTime =  DateFormat.getStrDate(date);
        pzEasyAccidentWithBLOBs.setCreatTime(creatTime);
        //创建人
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        pzEasyAccidentWithBLOBs.setCreatUser(user.getUserId());

        try{
            pzEasyAccidentMapper.insertSelective(pzEasyAccidentWithBLOBs);
            sysLogService.setPzLog(request,user.getUserId(),date,"1","3","易肇事肇祸严重精神障碍患者");
            json.setFlag(0);
            json.setMsg("插入信息成功，谢谢!");
        }catch(Exception e){
            e.printStackTrace();
            json.setMsg("插入信息错误，请重试!");
        }

        return json;
    }

    public ToJson<PzEasyAccidentWithBLOBs> updateInformation(HttpServletRequest request, PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<>(1, "error");
        try{
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            int result = pzEasyAccidentMapper.updateByPrimaryKeySelective(pzEasyAccidentWithBLOBs);
            sysLogService.setPzLog(request,user.getUserId(),new Date(),"3","3","易肇事肇祸严重精神障碍患者");
            if(result > 0){
                json.setFlag(0);
                json.setMsg("更新信息成功，谢谢！");
            }else{
                json.setMsg("更新信息失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("更新信息失败，请重试哦！");
        }
        return json;
    }

    public ToJson<PzEasyAccidentWithBLOBs> deleteInformation(HttpServletRequest request, Integer easyAccidentId){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<>(1, "error");
        try{
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            pzEasyAccidentMapper.deleteByPrimaryKey(easyAccidentId);
            sysLogService.setPzLog(request,user.getUserId(),new Date(),"2","3","易肇事肇祸严重精神障碍患者");
            json.setFlag(0);
            json.setMsg("删除信息成功，谢谢！");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("删除信息失败，请重试！");
        }
        return json;
    }

    public ToJson<PzEasyAccidentWithBLOBs> selectByLimit(HttpServletResponse response, HttpServletRequest request, PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs, Integer page, Integer pageSize, boolean useFlag, String export, String pCradId, String pName){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<>(1, "error");
        List<PzEasyAccidentWithBLOBs> list=null;
        try{
            if(export==null){
                export="0";
            }
            if(pzEasyAccidentWithBLOBs.getGridName()==null || pzEasyAccidentWithBLOBs.getGridName() == ""){
                PageParams pageParams=new PageParams();
                pageParams.setPage(page);
                pageParams.setPageSize(pageSize);
                pageParams.setUseFlag(useFlag);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("page", pageParams);
                map.put("pCradId", pCradId);
                map.put("pName", pName);
                Map<String, Object> param = new HashMap<String, Object>();
                Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                param.put("userId", user.getUserId());
                param.put("userPriv", user.getUserPriv());
                param.put("deptId", user.getDeptId());
                String menuModel=menuJdtMapper.selMenuByModel("4");
                if(!CheckAll.checkAll(menuModel,param)){
                    pzEasyAccidentWithBLOBs.setCreatUser(user.getUserId());
                }
                map.put("pzEasyAccidentWithBLOBs",pzEasyAccidentWithBLOBs);
                list=pzEasyAccidentMapper.selectByLimit(map);
                if(list.size()>0){
                    for(PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs1 : list){
                        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

                        if ("0".equals(pzEasyAccidentWithBLOBs1.getpSex())) {
                            pzEasyAccidentWithBLOBs1.setpSexStr("男");
                        } else {
                            pzEasyAccidentWithBLOBs1.setpSexStr("女");
                        }
                        if(pzEasyAccidentWithBLOBs1.getpDate()!=null){
                            pzEasyAccidentWithBLOBs1.setpDateStr(sdf.format(pzEasyAccidentWithBLOBs1.getpDate()));
                        }else{
                            pzEasyAccidentWithBLOBs1.setpDateStr("");
                        }

                        SysCode sysCode = sysCodeMapper.getSingleCode("DANGER_DEGREE", pzEasyAccidentWithBLOBs1.getDangerDegree());
                        if(sysCode!=null){
                            pzEasyAccidentWithBLOBs1.setDangerDegreeStr(sysCode.getCodeName());
                        }
                        if(StringUtils.checkNull(pzEasyAccidentWithBLOBs1.getFamilyEconomic())){
                            pzEasyAccidentWithBLOBs1.setFamilyEconomic("01");
                        }
                        SysCode sysCode1 = sysCodeMapper.getSingleCode("FAMILY_ECONOMIC", pzEasyAccidentWithBLOBs1.getFamilyEconomic());
                        if(sysCode!=null){
                            pzEasyAccidentWithBLOBs1.setFamilyEconomicStr(sysCode1.getCodeName());
                        }
                        SysCode sysCode2 = sysCodeMapper.getSingleCode("POLITICAL", pzEasyAccidentWithBLOBs1.getpPolitical());
                        if(sysCode2!=null){
                            pzEasyAccidentWithBLOBs1.setpPolitical(sysCode2.getCodeName());
                            pzEasyAccidentWithBLOBs1.setpPoliticalStr(sysCode2.getCodeName());
                        }
                        SysCode sysCode3 = sysCodeMapper.getSingleCode("DEGREE", pzEasyAccidentWithBLOBs1.getpEducation());
                        if(sysCode3!=null){
                            pzEasyAccidentWithBLOBs1.setpEducation(sysCode3.getCodeName());
                            pzEasyAccidentWithBLOBs1.setpEducationStr(sysCode3.getCodeName());
                        }
                        if ("01".equals(pzEasyAccidentWithBLOBs1.getpMaritalStatus())) {
                            pzEasyAccidentWithBLOBs1.setpMaritalStatusStr("未婚");
                        } else {
                            pzEasyAccidentWithBLOBs1.setpMaritalStatusStr("已婚");
                        }
                        if ("1".equals(pzEasyAccidentWithBLOBs1.getpVehicles())) {
                            pzEasyAccidentWithBLOBs1.setpVehiclesStr("有");
                        } else {
                            pzEasyAccidentWithBLOBs1.setpVehiclesStr("无");
                        }
                        SysCode sysCode4 = sysCodeMapper.getSingleCode("DANGER_DEGREE", pzEasyAccidentWithBLOBs1.getDangerDegree());
                        if(sysCode4!=null){
                            pzEasyAccidentWithBLOBs1.setDangerDegreeStr(sysCode4.getCodeName());
                        }
                        if(pzEasyAccidentWithBLOBs1.getFirstDate()!=null){
                            pzEasyAccidentWithBLOBs1.setFirstDateSrt(sdf.format(pzEasyAccidentWithBLOBs1.getFirstDate()));
                        }
                        SysCode sysCode5 = sysCodeMapper.getSingleCode("FAMILY_ECONOMIC", pzEasyAccidentWithBLOBs1.getFamilyEconomicStr());
                        if(sysCode5!=null){
                            pzEasyAccidentWithBLOBs1.setFamilyEconomicStr(sysCode5.getCodeName());
                        }
                        if ("0".equals(pzEasyAccidentWithBLOBs1.getAccidentHistory())) {
                            pzEasyAccidentWithBLOBs1.setAccidentHistoryStr("有");
                        } else  if ("1".equals(pzEasyAccidentWithBLOBs1.getAccidentHistory())){
                            pzEasyAccidentWithBLOBs1.setAccidentHistoryStr("无");
                        }
                        if ("0".equals(pzEasyAccidentWithBLOBs1.getAcceptTreatment())) {
                            pzEasyAccidentWithBLOBs1.setAcceptTreatmentStr("是");
                        } else  if ("1".equals(pzEasyAccidentWithBLOBs1.getAcceptTreatment())){
                            pzEasyAccidentWithBLOBs1.setAcceptTreatmentStr("否");
                        }
                        if ("0".equals(pzEasyAccidentWithBLOBs1.getSubsistenceAllowances())) {
                            pzEasyAccidentWithBLOBs1.setSubsistenceAllowancesStr("是");
                        } else  if ("1".equals(pzEasyAccidentWithBLOBs1.getSubsistenceAllowances())){
                            pzEasyAccidentWithBLOBs1.setSubsistenceAllowancesStr("否");
                        }

                    }

                    json.setObj(list);
                    json.setTotleNum(pageParams.getTotal());
                    json.setMsg("success");
                    json.setFlag(0);
                }
            }else {
                GridInfo gridInfo = gridInfoMapper.selectByUGridName(pzEasyAccidentWithBLOBs.getGridName());
                if(gridInfo != null){
                    pzEasyAccidentWithBLOBs.setGridId(gridInfo.getGridId());
                    PageParams pageParams=new PageParams();
                    pageParams.setPage(page);
                    pageParams.setPageSize(pageSize);
                    pageParams.setUseFlag(useFlag);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("page", pageParams);
                    map.put("pCradId", pCradId);
                    map.put("pName", pName);
                    Map<String, Object> param = new HashMap<String, Object>();
                    Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                    param.put("userId", user.getUserId());
                    param.put("userPriv", user.getUserPriv());
                    param.put("deptId", user.getDeptId());
                    String menuModel=menuJdtMapper.selMenuByModel("3");
                    if(!CheckAll.checkAll(menuModel,param)){
                        pzEasyAccidentWithBLOBs.setCreatUser(user.getUserId());
                    }
                    map.put("pzEasyAccidentWithBLOBs",pzEasyAccidentWithBLOBs);
                    list=pzEasyAccidentMapper.selectByLimit(map);
                    for(PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs1:list){
                        SysCode sysCode = sysCodeMapper.getSingleCode("DANGER_DEGREE", pzEasyAccidentWithBLOBs1.getDangerDegree());
                        if(sysCode!=null){
                            pzEasyAccidentWithBLOBs1.setDangerDegreeStr(sysCode.getCodeName());
                        }
                        SysCode sysCode1 = sysCodeMapper.getSingleCode("FAMILY_ECONOMIC", pzEasyAccidentWithBLOBs1.getFamilyEconomic());
                        if(sysCode!=null){
                            pzEasyAccidentWithBLOBs1.setFamilyEconomicStr(sysCode1.getCodeName());
                        }
                        if(!StringUtils.checkNull(pzEasyAccidentWithBLOBs1.getUserId())) {
                            pzEasyAccidentWithBLOBs1.setPzPerson(pzPersonMapper.selectByPrimaryKey(Integer.parseInt(pzEasyAccidentWithBLOBs1.getUserId().trim())));
                        }
                        if(!StringUtils.checkNull(pzEasyAccidentWithBLOBs1.getGridUserId())){
                            pzEasyAccidentWithBLOBs1.setUserName(usersService.getUserNameById(pzEasyAccidentWithBLOBs1.getGridUserId()));
                        }

                    }
                    if(list.size()>0){
                        json.setObj(list);
                        json.setTotleNum(pageParams.getTotal());
                        json.setMsg("success");
                        json.setFlag(0);
                    }
                }else {
                    json.setMsg("err");
                    json.setFlag(1);
                }
            }
            if(export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("易肇事肇祸严重精神障碍患者信息导出", 29);
                String[] secondTitles = { "所属网格","姓名","性别","身份证", "曾用名/别名", "出生日期","民族","联系方式","政治面貌","文化程度","婚姻状况","宗教信仰","职业","工作单位","户籍地址","籍贯","户籍地详址","现居地址","名下机动车辆","车牌号","备注", "危险程度","患病名称","初次发病日期","康复机构","家庭经济情况","有无肇事肇祸史","是否接受过治疗","治疗医院","是否纳入低保"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"gridName","pName","pSexStr","pCradId", "pAlias","pDateStr","pNation","pPhone","pPoliticalStr","pEducationStr","pMaritalStatusStr","pReligion","pOccupation","pWorkUnit","pDomicile","pOrigin","pDetailedDomicile","pAddress","pVehiclesStr","str1","pRemark", "dangerDegreeStr", "disease","firstDateSrt","rehabilitative","familyEconomicStr","accidentHistoryStr","acceptTreatmentStr","hospital","subsistenceAllowancesStr"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "易肇事肇祸严重精神障碍患者信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    public ToJson<PzEasyAccidentWithBLOBs> selectById(Integer easyAccidentId, HttpServletRequest request){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<>(1, "error");
        PzPerson pzPerson = new PzPerson();
        try{
            PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs =  pzEasyAccidentMapper.selectById(easyAccidentId);
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(pzEasyAccidentWithBLOBs.getAttachmentName()!=null&&!"".equals(pzEasyAccidentWithBLOBs.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(pzEasyAccidentWithBLOBs.getAttachmentName(),pzEasyAccidentWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_PZ_EASY);
            }
            pzEasyAccidentWithBLOBs.setAttachmentList(attachmentList);

            SysCode sysCode = sysCodeMapper.getSingleCode("POLITICAL", pzEasyAccidentWithBLOBs.getpPolitical());
            SysCode sysCode1 = sysCodeMapper.getSingleCode("DEGREE", pzEasyAccidentWithBLOBs.getpEducation());
            if(sysCode!=null){
                pzEasyAccidentWithBLOBs.setpPoliticalStr(sysCode.getCodeName());
            }

            if(sysCode1!=null){
                pzEasyAccidentWithBLOBs.setpEducationStr(sysCode1.getCodeName());
            }
            SysCode sysCode3 = sysCodeMapper.getSingleCode("DANGER_DEGREE", pzEasyAccidentWithBLOBs.getDangerDegree());
            if(sysCode3!=null){
                pzEasyAccidentWithBLOBs.setDangerDegreeStr(sysCode3.getCodeName());
            }
            SysCode sysCode4 = sysCodeMapper.getSingleCode("FAMILY_ECONOMIC", pzEasyAccidentWithBLOBs.getFamilyEconomic());
            if(sysCode4!=null){
                pzEasyAccidentWithBLOBs.setFamilyEconomicStr(sysCode4.getCodeName());
            }

            json.setMsg("ok");
            json.setObject(pzEasyAccidentWithBLOBs);
            json.setFlag(0);
        }catch(Exception e){
            e.printStackTrace();
            json.setMsg("查询信息失败，请重试！");
        }
        return  json;
    }

    /*
        导入方法
     */
    @Transactional
    public ToJson<PzEasyAccidentWithBLOBs> inputFixAsserts(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<PzEasyAccidentWithBLOBs>(1, "error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            //String name = rb.getString("mysql.driverClassName");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    /*file.transferTo(dest);*/
                    //将文件上传成功后进行读取文件
                    //进行读取的路径
                    String readPath = path.append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row rowObj = null;
                    int lastRowNum = sheetObj.getLastRowNum();
                    int inputFail=0;
                    int inputSuccess=0;
                    String faillReason="";
                    for (int i = 2; i <= lastRowNum; i++) {
                        rowObj = sheetObj.getRow(i);
                        if (rowObj != null) {
                            Cell c0 = rowObj.getCell(0);
                            Cell c1 = rowObj.getCell(1);
                            Cell c2 = rowObj.getCell(2);
                            Cell c3 = rowObj.getCell(3);
                            Cell c4 = rowObj.getCell(4);
                            Cell c5 = rowObj.getCell(5);
                            Cell c6 = rowObj.getCell(6);
                            Cell c7 = rowObj.getCell(7);
                            Cell c8 = rowObj.getCell(8);
                            Cell c9 = rowObj.getCell(9);
                            Cell c10 = rowObj.getCell(10);
                            if(c0.getStringCellValue()!=""&&c1.getStringCellValue()!=""&&c2.getStringCellValue()!=""){
                                PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs = new PzEasyAccidentWithBLOBs();
//                                if(!StringUtils.checkNull(c5.getStringCellValue())){
//                                    if(pzEasyAccidentMapper.selectById(Integer.parseInt(c0.getStringCellValue()))!=null){
//                                        pzEasyAccidentWithBLOBs.setLocationAddress(departmentMapper.getDeptById(Integer.parseInt(c5.getStringCellValue())).getDeptName());
//                                    }
//                                }
//                                pzEasyAccidentWithBLOBs.setAssetsName(c1.getStringCellValue());
//                                pzEasyAccidentWithBLOBs.setBuyTime(DateFormat.DateToStr(c2.getStringCellValue()));
//                                pzEasyAccidentWithBLOBs.setInfo(c3.getStringCellValue());
//                                pzEasyAccidentWithBLOBs.setNumber(Integer.valueOf(c4.getStringCellValue()));
//                                if(!StringUtils.checkNull(c5.getStringCellValue())){
//                                    if(departmentMapper.getDeptById(Integer.parseInt(c5.getStringCellValue()))!=null){
//                                        pzEasyAccidentWithBLOBs.setLocationAddress(departmentMapper.getDeptById(Integer.parseInt(c5.getStringCellValue())).getDeptName());
//                                    }
//                                }
//                                pzEasyAccidentWithBLOBs.setInfo(c7.getStringCellValue());
//                                pzEasyAccidentWithBLOBs.setRemake(c8.getStringCellValue());
//                                if(!StringUtils.checkNull(c9.getStringCellValue())){
//                                    if(usersMapper.findUsersByuserId(c9.getStringCellValue())!=null){
//                                        pzEasyAccidentWithBLOBs.setCreater(usersMapper.findUsersByuserId(c9.getStringCellValue()).getUserId());
//                                    }
//                                }
//                                if(!StringUtils.checkNull(c10.getStringCellValue())){
//                                    pzEasyAccidentWithBLOBs.setCreaterTime(DateFormat.DateToStr(c10.getStringCellValue()));
//                                }
//                                if(eduFixAssetsMapper.selFixAssetsById(c0.getStringCellValue())!=null){
//                                    eduFixAssetsMapper.insert(pzEasyAccidentWithBLOBs);
//                                    inputSuccess++;
//                                }else {
//                                    inputFail++;
//                                    faillReason+=c0.getStringCellValue()+",";
//                                    continue;
//                                }
                            }
                        }
                    }
                    PzEasyAccidentWithBLOBs temp=new PzEasyAccidentWithBLOBs();
                    temp.setInputFail(inputFail);
                    temp.setInputSuccess(inputSuccess);
                    temp.setFaillReason(faillReason);
                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("0");//文件类型不正确
                    return json;
                }
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("EduFixAssetsService inputFixAsserts:"+e);
            e.printStackTrace();
        }
        return json;
    }
    /*
        导出方法
     */
    public ToJson<PzEasyAccidentWithBLOBs> selFixAssetsByCond(int condition, int output, PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs, HttpServletRequest request, HttpServletResponse response, HttpSession session, Integer page, Integer pageSize, boolean useFlag){
        ToJson<PzEasyAccidentWithBLOBs> json = new ToJson<PzEasyAccidentWithBLOBs>(1, "error");
        try{
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("pzEasyAccidentWithBLOBs",pzEasyAccidentWithBLOBs);
            List<PzEasyAccidentWithBLOBs> pzEasyAccidentWithBLOBsList=new ArrayList<PzEasyAccidentWithBLOBs>();

            if(output==1) {//output==1,则进行导出操作
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("易肇事肇祸严重精神障碍患者信息表", 12);
                String[] secondTitles = {"危险程度", "患病名称","初次发病日期","康复机构","家庭经济状况","有无肇事肇祸史","是否接受过治疗","治疗医院","是否纳入低保"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"dangerDegree","disease","firstDate","rehabilitative","familyEconomic","accidentHistory","acceptTreatment","hospital","subsistenceAllowances"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, pzEasyAccidentWithBLOBsList, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = response.getOutputStream();

                String filename = "易肇事肇祸严重精神障碍患者信息表.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }
            json.setObj(pzEasyAccidentWithBLOBsList);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  json;
    }

    public ToJson importEasyAccident(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzEasyAccidentWithBLOBs> toJson = new ToJson<PzEasyAccidentWithBLOBs>(1, "error");
        Users users= SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件！");
                toJson.setFlag(1);
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
               //     String readPath = path.append(newFileName).toString();
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<PzEasyAccidentWithBLOBs> saveList = new ArrayList<PzEasyAccidentWithBLOBs>();
                    List<PzPersonWithBLOBs> saveList1 = new ArrayList<PzPersonWithBLOBs>();
                    PzEasyAccidentWithBLOBs pzEasyAccidentWithBLOBs = null;
                    PzPersonWithBLOBs pzPersonWithBLOBs = null;
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
                    SysCode sysCode=new SysCode();
                    int count=0;
                    for (int i = 1; i <lastRowNum; i++) {
                        pzEasyAccidentWithBLOBs = new PzEasyAccidentWithBLOBs();
                        pzPersonWithBLOBs = new PzPersonWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属网格
                                            String as=cell.getStringCellValue().trim();
                                            GridInfo info=gridInfoMapper.selectByUGridName(as);
                                            pzPersonWithBLOBs.setpGrid(info.getGridId());
                                            pzEasyAccidentWithBLOBs.setGridId(info.getGridId());
                                            break;
                                        case 1:
                                            // 姓名
                                            pzPersonWithBLOBs.setpName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            // 身份证
                                            pzPersonWithBLOBs.setpCradId(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            // 别名
                                            pzPersonWithBLOBs.setpAlias(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            // 性别
                                            if("男".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("0");
                                            }else if("女".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpSex("1");
                                            }
                                            break;
                                        case 5:
                                            // 出生日期
                                            pzPersonWithBLOBs.setpDate(sd.parse(cell.getStringCellValue().trim()));
                                            break;
                                        case 6:
                                            // 民族
                                            pzPersonWithBLOBs.setpNation(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            // 联系方式
                                            if (cell.getCellType() ==CellType.NUMERIC) {
                                                BigDecimal bigP=new BigDecimal(cell.getNumericCellValue());
                                                value = bigP.toString();
                                                //解决1234.0  去掉后面的.0
                                                if(null!=value&&!"".equals(value.trim())){
                                                    String[] item = value.split("[.]");
                                                    if(1<item.length&&"0".equals(item[1])){
                                                        value=item[0];
                                                    }
                                                }
                                                pzPersonWithBLOBs.setpPhone(value);
                                            }else {
                                                pzPersonWithBLOBs.setpPhone(cell.getStringCellValue());
                                            }
                                            break;
                                        case 8:
                                            // 政治面貌

                                            sysCode.setParentNo("POLITICAL");
                                            sysCode.setCodeName(cell.getStringCellValue().trim());
                                            pzPersonWithBLOBs.setpPolitical(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                                            break;
                                        case 9:
                                            // 文化程度
                                            sysCode.setParentNo("DEGREE");
                                            sysCode.setCodeName(cell.getStringCellValue().trim());
                                            pzPersonWithBLOBs.setpEducation((sysCodeMapper.getCodeNoByNameAndParentNo(sysCode)).getCodeNo());
                                            break;
                                        case 10:
                                            // 婚姻状况
                                            if("未婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("01");
                                            }else if("已婚".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpMaritalStatus("02");
                                            }
                                            break;
                                        case 11:
                                            //宗教信仰
                                            pzPersonWithBLOBs.setpReligion(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //职业
                                            pzPersonWithBLOBs.setpOccupation(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //工作单位
                                            pzPersonWithBLOBs.setpWorkUnit(cell.getStringCellValue());
                                            break;
                                        case 14:
                                            //户籍地址
                                            pzPersonWithBLOBs.setpDomicile(cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //籍贯
                                            pzPersonWithBLOBs.setpOrigin(cell.getStringCellValue());
                                            break;
                                        case 16:
                                            //户籍地详址
                                            pzPersonWithBLOBs.setpDetailedDomicile(cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //名下机动车辆
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpVehicles("1");
                                            }
                                            break;
                                        case 18:
                                            //备注
                                            pzPersonWithBLOBs.setpRemarks(cell.getStringCellValue());
                                            break;
                                        case 19:
                                            //有无固定住所
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("0");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setpIsHouse("1");
                                            }
                                            break;
                                        case 20:
                                            //现居地址
                                            pzPersonWithBLOBs.setpAddress(cell.getStringCellValue());
                                            break;
                                        case 21:
                                            //实口类型
                                            if("流动人口".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setFlag1("2");
                                            }else if("户籍人口".equals(cell.getStringCellValue().trim())){
                                                pzPersonWithBLOBs.setFlag1("1");
                                            }
                                            break;
                                        case 22:
                                            //车牌号
                                            cell.setCellType(CellType.STRING);
                                            pzPersonWithBLOBs.setStr1(cell.getStringCellValue());
                                            break;
                                        case 23:
                                            // 危险程度
                                            sysCode.setParentNo("DANGER_DEGREE");
                                            sysCode.setCodeName(cell.getStringCellValue().trim());
                                            pzEasyAccidentWithBLOBs.setDangerDegree((sysCodeMapper.getCodeNoByNameAndParentNo(sysCode)).getCodeNo());
                                            break;
                                        case 24:
                                            // 患病名称
                                            pzEasyAccidentWithBLOBs.setDisease(cell.getStringCellValue());
                                            break;
                                        case 25:
                                            // 初次发病日期
                                            //Date dates=cell.getDateCellValue();
                                            cell.setCellType(CellType.STRING);
                                            pzEasyAccidentWithBLOBs.setFirstDate(sd.parse(cell.getStringCellValue().trim()));
                                            break;
                                        case 26:
                                            // 康复机构
                                            pzEasyAccidentWithBLOBs.setRehabilitative(cell.getStringCellValue());
                                            break;
                                        case 27:
                                            // 家庭经济情况
                                            sysCode.setParentNo("FAMILY_ECONOMIC");
                                            sysCode.setCodeName(cell.getStringCellValue().trim());
                                            pzEasyAccidentWithBLOBs.setFamilyEconomic((sysCodeMapper.getCodeNoByNameAndParentNo(sysCode)).getCodeNo());
                                            break;
                                        case 28:
                                            // 有无肇事肇祸史
                                          //  pzEasyAccidentWithBLOBs.setAccidentHistory(cell.getStringCellValue());
                                            if("无".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setAccidentHistory("1");
                                            }else if("有".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setAccidentHistory("0");
                                            }
                                            break;
                                        case 29:
                                            // 是否接受过治疗
                                            //pzEasyAccidentWithBLOBs.setAcceptTreatment(cell.getStringCellValue());
                                            if("否".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setAcceptTreatment("1");
                                            }else if("是".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setAcceptTreatment("0");
                                            }
                                            break;
                                        case 30:
                                            //治疗医院
                                            pzEasyAccidentWithBLOBs.setHospital(cell.getStringCellValue());
                                            break;
                                        case 31:
                                            //是否纳入低保
                                          //  pzEasyAccidentWithBLOBs.setSubsistenceAllowances(cell.getStringCellValue());
                                            if("否".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setSubsistenceAllowances("1");
                                            }else if("是".equals(cell.getStringCellValue().trim())){
                                                pzEasyAccidentWithBLOBs.setSubsistenceAllowances("0");
                                            }
                                            break;
                                        default:
                                            toJson.setFlag(0);
                                            toJson.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            List<String> nullArray=new ArrayList();
                            if(pzPersonWithBLOBs.getpGrid()==null){
                                nullArray.add("特殊网格");
                            }
                            if(pzPersonWithBLOBs.getpName()==null){
                                nullArray.add("姓名");
                            }
                            if(pzPersonWithBLOBs.getpSex()==null){
                                nullArray.add("性别");
                            }
                            if(pzPersonWithBLOBs.getpCradId()==null){
                                nullArray.add("身份证号");
                            }
                            if(pzPersonWithBLOBs.getFlag1()==null){
                                nullArray.add("实口类型");
                            }
                            if(pzPersonWithBLOBs.getpOrigin()==null){
                                nullArray.add("籍贯");
                            }
                            if(pzPersonWithBLOBs.getpIsHouse()==null){
                                nullArray.add("有无固定住所");
                            }
                            if(pzPersonWithBLOBs.getpAddress()==null){
                                nullArray.add("现居地址");
                            }
                            if(pzPersonWithBLOBs.getpMaritalStatus()==null){
                                nullArray.add("婚姻状况");
                            }
                            if(pzPersonWithBLOBs.getpDomicile()==null){
                                nullArray.add("户籍地址");
                            }
                            if(pzPersonWithBLOBs.getpDetailedDomicile()==null){
                                nullArray.add("户籍地详情");
                            }
                            if(pzPersonWithBLOBs.getpVehicles()==null){
                                nullArray.add("名下机动车辆");
                            }
                            if(pzEasyAccidentWithBLOBs.getDangerDegree()==null){
                                nullArray.add("危险程度");
                            }
                            if(pzEasyAccidentWithBLOBs.getAccidentHistory()==null){
                                nullArray.add("有无肇事肇祸史");
                            }
                            if(pzEasyAccidentWithBLOBs.getSubsistenceAllowances()==null){
                                nullArray.add("是否纳入低保");
                            }
                            if(pzEasyAccidentWithBLOBs.getAcceptTreatment()==null){
                                nullArray.add("是否接受过治疗");
                            }
                            if(nullArray.size()>0){
                                toJson.setObject(nullArray);
                                toJson.setMsg("必填字段不能为空，请重新导入");
                            }else {
                                //判断用户是否为空，不为空判断用户是否存在
                                if(!StringUtils.checkNull(pzPersonWithBLOBs.getpName())&&!StringUtils.checkNull(pzPersonWithBLOBs.getpCradId())){
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("pCradId", pzPersonWithBLOBs.getpCradId());
                                    map.put("pName", pzPersonWithBLOBs.getpName());
                                    PzPersonWithBLOBs pzPersons=pzPersonMapper.selectPersonCountByNameCrad(map);
                                    if(pzPersons.getCount()>0){
                                        pzPersonWithBLOBs.setpId(pzPersons.getpId());
                                        pzPersonWithBLOBs.setFlag2("0");
                                        if(!pzPersons.getSpecialStr().contains("4,")){
                                            String str = "4," + pzPersons.getSpecialStr();
                                            pzPersonWithBLOBs.setSpecialStr(str);
                                        }
                                        pzEasyAccidentWithBLOBs.setUserId(String.valueOf(pzPersons.getpId()));
                                        pzPersonMapper.updateByPrimaryKeySelective(pzPersonWithBLOBs);
                                    }else {
                                        //创建用户和创建时间
                                        pzPersonWithBLOBs.setCreateUser(users.getUserId());
                                        pzPersonWithBLOBs.setCreateTime(DateFormat.getCurrentTime());
                                        pzPersonWithBLOBs.setFlag2("0");
                                        pzPersonWithBLOBs.setSpecialStr("4,");
                                        pzPersonMapper.insertSelective(pzPersonWithBLOBs);
                                        pzEasyAccidentWithBLOBs.setUserId(String.valueOf(pzPersonWithBLOBs.getpId()));
                                    }
                                }
                                //将数据放入数据库
                                //用户表与肇事表关联用户userid
                                pzEasyAccidentWithBLOBs.setUserId(String.valueOf(pzPersonWithBLOBs.getpId()));
                                //判断关联用户userid是否为空,为空新增,不为空修改
                                if(!StringUtils.checkNull(pzEasyAccidentWithBLOBs.getUserId())){
                                    //如果不为空，查询是否有肇事信息，有则更新，否则新增
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("userId", pzEasyAccidentWithBLOBs.getUserId());
                                    PzEasyAccident pzEasy=pzEasyAccidentMapper.selectByUserId(map);
                                    if(pzEasy.getCou()>0){
                                        pzEasyAccidentWithBLOBs.setEasyAccidentId(pzEasy.getEasyAccidentId());
                                        count +=pzEasyAccidentMapper.updateByPrimaryKeySelective(pzEasyAccidentWithBLOBs);
                                    }else {
                                        //创建用户和创建时间
                                        pzEasyAccidentWithBLOBs.setCreatUser(users.getUserId());
                                        pzEasyAccidentWithBLOBs.setCreatTime(DateFormat.getCurrentTime());
                                        count += pzEasyAccidentMapper.insertSelective(pzEasyAccidentWithBLOBs);
                                    }
                                }
                            }
                        }
                    }
                    if(count>0) {
                        successCount = successCount + count;
                    }
                    dest.delete();
                    if(successCount>0){
                        toJson.setTotleNum(successCount);
                        toJson.setMsg("ok");
                        toJson.setFlag(0);
                        return  toJson;
                    }
                }
            }
        } catch (Exception e) {
            //读取配置文件,获取文件要存储的路径
            StringBuffer path = this.getPath();
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String extName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);// 文件后缀
                String newFileName = uuid + extName;//组合成新的文件名
                File dest = new File(path.toString(), newFileName);
                dest.delete();
            }
            e.getMessage();
            e.printStackTrace();
        }

        return toJson;
    }

    //判读当前系统,读取配置文件,返回路径
    public StringBuffer getPath(){
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer path = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            path = path.append(rb.getString("upload.win"));
        } else {
            path = path.append(rb.getString("upload.linux"));
        }
        return path;
    }
}
